<template>
  <div class="task-drawer" v-if="show" v-draggable>
    <div class="header flex alignCenter between">
       <div class="title">
         上传任务
       </div>
      <div class="tools flex between alignCenter">
<!--        <MinusOutlined />-->
        <CloseOutlined @click="show=false"/>
      </div>
    </div>
    <div class="task-list">
      <div class="task-item flex alignCenter between"
      v-for="(item,index) in uploadQueueList"
           :key="index"
      >
        <div class="left single-line">
          <img src="https://file.qcycloud.xyz/fileThumbnail/mp4.png"/>
          <span class="fileName">{{item.fileName}}</span>
        </div>
        <div class="content flex alignCenter between">
          <div class="fileSize">
            {{formatFileSize(item.fileSize)}}
          </div>
          <div class="status">
            {{item.runningState===1?item.percent+"%":'暂停'}}
          </div>
        </div>
        <div class="tools flex alignCenter end">
          <CaretRightOutlined v-if="!item.runningState||item.runningState===2" @click="pause(item.uploadId)"/>
          <PauseOutlined v-else @click="pause(item.uploadId)"/>
          <CloseOutlined @click="stopTask(item.uploadId)"/>
        </div>
      </div>
    </div>
  </div >
  <a-progress class="round" type="circle" :percent="currentTask.percent"
              size="small"
              @click="show=true"
              v-draggable v-else
              strokeColor="#1677ff"
              :success="{
                 strokeColor:'#1677ff'
              }"
  >
    <template #format="percent">
     <div style="position: relative">
       <div class="flex alignCenter column center single-line"

       >
         <span style="font-size: 12px" v-if="showPercent"> {{percent}}%</span>
         <div  v-else>
          <span v-if="uploadQueueList.length===0" style="font-size: 12px">
            无任务
          </span>
           <span v-if="currentTask&&(currentTask.runningState===0||!currentTask.runningState&&uploadQueueList.length>0)" style="font-size: 12px">
            待上传
          </span>
           <span v-if="currentTask&&currentTask.runningState===1" style="font-size: 12px">
            上传中
          </span>
         </div>


       </div>
<!--       <div class="wave"></div>-->
     </div>
    </template>

  </a-progress>

</template>
<script setup lang="ts">

import {computed, defineComponent, ref, watch} from "vue";
import useSystemStore from '@/stroe/system.ts'
import {getFileSize} from '@/utils/fileUtils.ts'
import {UploadQueueItem,Part} from  '@/types/files.ts'
import {uploadPartFile,completeUploadTask,stopUploadTask} from '@/api/disk/disk.ts'
import {
  MinusOutlined,CloseOutlined,
  PauseOutlined,CaretRightOutlined
} from '@ant-design/icons-vue';
defineComponent({
  MinusOutlined,CloseOutlined,
  PauseOutlined,CaretRightOutlined
})
interface UploadTask extends UploadQueueItem{
  runningState:number; //运行状态
  percent:any; // 进度,
  runIndex:number // 运行到第几个part
}
const systemStore = useSystemStore();
const show = ref(false);
const showPercent = ref(false);
const hiddenTask = ref(null)
const uploadQueue = computed(()=>systemStore.uploadQueue);
const uploadQueueList = ref<UploadTask[]>([]);

const currentTask = ref<UploadTask>({} as UploadTask)


  const formatFileSize = (size)=>{
    return getFileSize(size);
  }

watch(()=>show.value,(value)=>{
  if(value&&hiddenTask.value) {
    clearInterval(hiddenTask.value);
    hiddenTask.value = null;
    return
  }

},{immediate:true})




const runSubTask = (partList:Part[],uploadId:string)=>{
  const arr:any =[];
  partList.forEach(item=>{
    arr.push(new Promise(resolve => {
      uploadPartFile(
          uploadId,item.blob as File,
          {partNumber:item.partNumber,hash:item.hash
          }).then(()=>{
        resolve(`执行第${item.partNumber}块`);
      })
      /*setTimeout(()=>{
        console.log(`执行第${item.partNumber}块`)
        resolve(`执行第${item.partNumber}块`);
      },2000)*/
    }))
  })
  return new Promise((resolve) => {
    Promise.all(arr).then(res=>{
      resolve(res);
    })
  })
}

const stopTask =(uploadId:string)=>{
  stopUploadTask(uploadId)
  uploadQueueList.value =  uploadQueueList.value.filter(item=>item.uploadId!==uploadId)
}
const pause = (uploadId:string)=>{
  const index = uploadQueueList.value.findIndex(item=>item.uploadId === uploadId);
  const task = uploadQueueList.value[index];
  uploadQueueList.value[index].runningState = task.runningState===1?2:1
  if(uploadQueueList.value[index].runningState===1){
    runTask(uploadId);
  }
}
const completeTask = (uploadId:string)=>{
  const task = uploadQueueList.value.find(item=>item.uploadId===uploadId)
  uploadQueueList.value =  uploadQueueList.value.filter(item=>item.uploadId!==uploadId)
  completeUploadTask(uploadId,{fileSize:task?.fileSize}).then(res=>{
    const arr:UploadQueueItem[] = [];
    uploadQueueList.value.forEach(item=>{
      const task = uploadQueue.value.find(ite=>ite.uploadId===item.uploadId)
      if(task){
        arr.push(task as UploadQueueItem)
      }
    })
    systemStore.setUploadQueue(arr)
  })

}
const runTask = async (uploadId:string)=>{
  const index = uploadQueueList.value.findIndex(item=>item.uploadId === uploadId)
  if(index===-1){
    console.log(`任务:${uploadId} 已停止`)
    return;
  }
  const task:UploadTask = {...uploadQueueList.value[index]};

  if(task.runningState===2){
    console.log(`任务:${uploadId} 已暂停`)
    return;
  }
  task.runningState = 1;
  const startIndex =  task.runIndex? task.runIndex :0;
  let endIndex = startIndex+1;
  if(endIndex>task.partList.length){
    endIndex = task.partList.length
  }

  const taskArr = task.partList.slice(startIndex,endIndex)
  await runSubTask(taskArr,task.uploadId);

    task.runIndex = endIndex ;
    task.percent = (endIndex / task.partList.length * 100).toFixed(2)
    if(task.runIndex===task.partList.length){
      completeTask(task.uploadId)
      return;
    }

    const task2 = uploadQueueList.value.find(item=>item.uploadId === uploadId);
    // 外部没有改变状态才更新
    if(task2&&task2.runningState===task.runningState||task2&&task2.runningState===0){
      uploadQueueList.value[index] = {...task}
    }

    runTask(uploadId);





}
const onbeforeunload = (e)=>{
  // 你的确认消息
  const confirmationMessage = '确定要离开页面吗？';

  // 设置事件的返回消息（显示给用户的提示）
  e.returnValue = confirmationMessage;
  return confirmationMessage;
}
watch(()=>uploadQueueList.value,(value)=>{
  currentTask.value = value.find(item=>item.runningState===1)||{} as UploadTask;
  if(value.length===0){
    window.removeEventListener("beforeunload",onbeforeunload);
    return;
  }
  if (!(window.onbeforeunload !== null && typeof window.onbeforeunload !== 'undefined')) {
    window.addEventListener("beforeunload",onbeforeunload)
  }

},{
  immediate:true,
  deep:true
})

watch(()=>uploadQueue.value,(value)=>{
  const oldIds = uploadQueueList.value.map(item=>item.uploadId);

  value.forEach((item)=>{
    if(!oldIds.includes(item.uploadId)){
      uploadQueueList.value.push({
        ...item,
        percent:0,
        runningState:0
      } as UploadTask)
    }
  })
  const runningNum = uploadQueueList.value.filter(item=>item.runningState===1).length;
  const nextTask = uploadQueueList.value.filter(item=>item.runningState===0).shift();
  // 最多同时执行3个任务
  if(runningNum<3&&nextTask){
    runTask(nextTask.uploadId)
  }

},{
  immediate:true,
  deep:true
})


</script>
<style scoped lang="scss">
/*.task-drawer:hover{
  cursor: move;
}*/
.single-line {
  white-space: nowrap;       /* 禁止换行 */
  overflow: hidden;          /* 隐藏超出部分 */
  text-overflow: ellipsis;   /* 显示省略号 */
}

.task-drawer{
  width: 400px;
  height: 500px;
  //background-color: #000;
  position: absolute;
  bottom: 20px;
  right: 20px;

  background: #fff;
  box-shadow: 0 0 16px 0 rgba(54, 58, 80, .16);
  z-index: 999;
  .header{
    padding: 10px 20px;
    height: 40px;
    background-color: #1677ff;
    background-image: url("@/assets/images/task_header_bg.png");
    background-repeat: no-repeat;
    background-position: 100% 100%;
    cursor: move;
    .title{
      font-size: 20px;
      font-weight: bold;
      color: #fff;
    }
    .tools{
      //width: 30px;
      height: 100%;
      cursor: pointer;
      .anticon{
        font-size: 14px;
        color:#fff
      }
    }
  }
  .task-list{
    .task-item{
      padding: 15px 20px;
      border-bottom: 1px solid #e3e3e3;
      font-size: 12px;
      .left{
        width: 53%;
        img{
          width: 30px;
          height: 30px;
          border-radius: 10px;
          margin-right: 10px;
        }
        .fileName{
          //font-size: 12px;
        }
      }
      .content{
        width: 27%;
      }
      .tools{
        width: 20%;
        .anticon{
          font-size: 14px;
        }
        .anticon:nth-child(1){
          margin-right: 20px;
        }
      }
    }
  }
}
.round{
  width: 60px;
  height: 60px;
  position: absolute;
  right: 20px;
  top: 50%;
  border-radius: 50%;
  background-color: #fff;
  cursor: pointer;
  font-size: 12px;
  color: #fff;
  z-index: 999;
  .wave {
    position: absolute;
    top: 31px;
    left: 0;
    width: 50px;
    height: 50px;
    background: rgb(168, 168, 231);
    border-radius: 40%;
    animation: rotateAnimation-7317d8dc 2s linear infinite;
    transform: translate(-50%, -50%);
  }
}
 :deep(.ant-progress-text) span{
  color:#000000;
}
@keyframes rotateAnimation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
